const Promise = require('bluebird'); //
const JiraTool = require('../Tools/JiraTool');
const Pool = require('../Tools/Pool').Pool;
const PoolJira=require('../Tools/Pool').PoolJira;
const TimeTool = require('../Tools/TimeTool');
const JiraDBPool = require('../Tools/JiraPool');

const Project = require('./Project');
const TestRecord = require('./TestRecord');
const TestReport = require('./TestReport');

const _ = require('lodash');
const {jira,user} = require('../Configs');


let request = require('request');
request = Promise.promisifyAll(request); //

const {
  JIRA_HOST
} = jira;

/**
 * Jira相关请求和数据库操作
 */
class JiraModel {
  constructor() {

    this.retsinglebugtotal = null;
    this.retSingleProjectName = null;
    this.retsingleWeekGrowth = null;
    this.retsingleDayGrowth = null;
    this.retsingleHandingRate = null;
    this.retsingleHandingDayGrowth = null;
    this.retsingleHandingWeeKGrowth = null;
    this.retsingleMonthDetail = null;
    this.retsingleMonthTotal = null;
    this.retsingleMonthMax = null;
    this.retsingleDayAverage = null;
    this.retsingleMonthTotalBug = null;
    this.retsingqualitRegressionTestRate = null;
    this.retsingqualitqualityHandingRate = null;

  }

  /**
   * 从数据库中获取最新的一条Jira数据
   */
  async getJiraSql() {

    let sql = 'SELECT * FROM jira ORDER BY id DESC LIMIT 1';
    let data = await Pool.queryAsync(sql);
    let ret = data[0];
    for (let i in ret) {
      if (typeof ret[i] == 'string') {
        ret[i] = JSON.parse(ret[i])
      }
    };
    return ret;
  }

  async getSingleProjectTableSql(projectid) {

    let sql = `SELECT * FROM singleproject WHERE singleporjectId=${projectid} ORDER BY id DESC LIMIT 1`;
    let data = await Pool.queryAsync(sql);
    let ret = data[0];
    for (let i in ret) {
      if (i == 'singlebugMonthDetail') {
        ret[i] = JSON.parse(ret[i])
      }
    };
    return ret;


  }

  async  getQualityfactorTabelSql() {

    let sql = `SELECT  qualitysum from qualityfactor ORDER BY id DESC LIMIT 1;`;
    let data = await Pool.queryAsync(sql);
    let ret = data[0];

    for (let i in ret) {
      if (typeof ret[i] == 'string') {
        ret[i] = JSON.parse(ret[i])
      }
    };
    return ret;

  }



  /**
   * 根据传入JQL从Jira服务器上获取相关Bug数据
   */
  async getBugByJql(params) {

    let api = `${JIRA_HOST}/rest/api/2/search?maxResults=0`
    if (params) {
      api = JiraTool.addParams(api, params);
    };
    let res = await request.getAsync(api, user);
    let ret = JiraTool.bodyParser(res);
    return ret

  };


  /**
   * 根据传入Project_ID获取相关项目数据，
   * 如不传入参数则获取所有
   */
  async getProjectById(id) {

    let api = `${JIRA_HOST}/rest/api/2/project`;
    if (id) {
      api += `/${id}`;
    };
    let res = await request.getAsync(api, user);
    let ret = JSON.parse(res.body);
    let filterIDRet = await JiraTool.filterID(ret)
    return filterIDRet;
  }


  // 带id参数
  async getProjectByIdparma(id) {

    let api = `${JIRA_HOST}/rest/api/2/project/${id}`;
    let res = await request.getAsync(api, user);
    let ret = JSON.parse(res.body);

    return ret;
  }

  /**
   * 根据传入Component_ID获取相关模块数据
   */
  async getComponentById(id) {
    let api = `${JIRA_HOST}/rest/api/2/component/${id}/relatedIssueCounts`;
    let res = await request.getAsync(api, user);
    let ret = JiraTool.bodyParser(res);
    return ret;
  }

  /**
   * 从jira数据库统计issue自定义字段的数量
   */
  async getCountByCustomField(customfield) {
    let sql = `SELECT
    *, COUNT(customvalue) AS custom_value_count
    FROM
    (SELECT 
    jiraissue.id AS issueid,project.id AS pid, project.pname,customfieldoption.customvalue
    FROM
    jiraissue, customfield, customfieldoption, customfieldvalue, project
    WHERE
    jiraissue.ID=customfieldvalue.ISSUE
    AND
    customfieldvalue.STRINGVALUE=customfieldoption.ID
    AND
    customfieldoption.CUSTOMFIELD=customfield.ID
    AND jiraissue.PROJECT=project.ID
    AND customfield.cfname="${customfield}")
    AS issuecustomfield
    GROUP BY issuecustomfield.pname,issuecustomfield.customvalue`;
    try {
      let rows = await JiraDBPool.queryAsync(sql);
      let countResult = rows.map((row) => {
        return {
          pid: row.pid,
          pname: row.pname,
          customValue: row.customvalue,
          customValueCount: row.custom_value_count
        }
      })
      return countResult;
    } catch (error) {
      throw error;
    }
  }


  /**
   * 根据传入Project_ID获取相关项目的版本信息
   */
  async getProjectVersionsById(id) {
    let api = `${JIRA_HOST}/rest/api/2/project/${id}/versions`;
    let res = await request.getAsync(api, user);
    let ret = JiraTool.bodyParser(res);
    return ret;
  }



  async getSingleProjectData() {

    let idArry = [];
    let res = this.getProjectById();
    for (let i = 0; i < res.length; i++) {
      idArry.push(res[i].id)
    }

    return idArry

  }


  // 插入jir数据
  async saveToSql(data) {

    let keys = [];
    let args = [];
    for (let i in data) {
      keys.push(i);
      if (typeof data[i] == 'object') {
        data[i] = JSON.stringify(data[i]);
      };
      args.push(data[i]);
    };

    let sqlKeysStr = keys.join(',');

    let sqlArgsStr = [];
    for (let i in keys) {
      sqlArgsStr.push('?');
    };
    sqlArgsStr = sqlArgsStr.join(',');


    let sql = `INSERT INTO jira (${sqlKeysStr}) VALUES (${sqlArgsStr})`;
    await Pool.queryAsync(sql, args);

  };


  async projectIdPushArray(AllProjectObject) {

    let idArry = []
    for (let i = 0; i < AllProjectObject.length; i++) {
      idArry.push(AllProjectObject[i].id)

    }
    return idArry
  };







  //根据传入的ID插入不同维护的数据，并查询对应记录

  async saveSingleBugToSql(idArry) {

    try{
    this.retsinglebugtotal = await this.getSingleBugByJql(idArry)
    
    this.retSingleProjectName = await this.getSingleProjectName(idArry)
    
    this.retsingleWeekGrowth = await this.getSingleBugNumWeekGrowth(idArry)
   
    this.retsingleDayGrowth = await this.getSingleBugNumDayGrowth(idArry)
    
    this.retsingleHandingRate = await this.getBugSingleHandingRate(idArry)
    
    this.retsingleHandingDayGrowth = await this.getBugSingleHandingDayGrowth(idArry)
    
    this.retsingleHandingWeeKGrowth = await this.getBugSingleHandingWeekGrowth(idArry)
    
    this.retsingleMonthDetail = await this.getBugSingleMonthDetail(idArry)
    
    this.retsingleMonthTotal = await this.getSingleBugMonthTotal(idArry)
    
    this.retsingleMonthMax = await this.getSingleBugMonthMax(idArry)
    
    this.retsingleDayAverage = await this.getSingleBugDayAverage(idArry)
    
    this.retsingleMonthTotalBug = await this.getProjectEachMonthTotalBug(idArry)
    
    this.retsingqualitRegressionTestRate  =await this.SinglequalityRegressionTestRate(idArry)
    
    this.retsingqualitqualityHandingRate = await this.SinglequalityHandingRate(idArry)
    
    }
    catch (err){
      throw  err
      console.log('err',err)
    }
    for (let i = 0; i < idArry.length; i++) {

      let sql2 = 'INSERT INTO singleproject(singleporjectId,singleprojectName,singlebugTotal,singlebugNumWeekGrowth,singlebugNumDayGrowth,singlebugHandingRate,singlebugHandingDayGrowth,singlebugHandingWeekGrowth,singlebugMonthDetail,singlebugMonthTotal,singlebugMonthMax,singleBugDayAverage,singleBugMonthTotalBug,singlequalityRegression,singlequalityHandingRate) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) '

      let args = [idArry[i], this.retSingleProjectName[i], this.retsinglebugtotal[i], this.retsingleWeekGrowth[i], this.retsingleDayGrowth[i], this.retsingleHandingRate[i],
      this.retsingleHandingDayGrowth[i], this.retsingleHandingWeeKGrowth[i], JSON.stringify(this.retsingleMonthDetail[i]),
      this.retsingleMonthTotal[i], this.retsingleMonthMax[i], this.retsingleDayAverage[i], JSON.stringify(this.retsingleMonthTotalBug[i]), JSON.stringify(this.retsingqualitRegressionTestRate[i]), JSON.stringify(this.retsingqualitqualityHandingRate[i])
      ]

      let rrrre = await Pool.queryAsync(sql2, args);

    }

  }

  async  saveQualityfactorToSql(idArry) {
    let qualityHandingRate = await this.SinglequalityHandingRate(idArry)

    let bfbarry = await this.SinglequalityRegressionTestRate(idArry)

    let TestCoverage = await this.SingleTestCoverage(idArry)

    let MeasureQuality = await this.SingleMeasureQuality(idArry)

    let TestPassRate = await this.SingleTestPassRate(idArry)

    let LeakRateMeasurement = await this.SingleLeakRateMeasurement(idArry)

    let sumarry = bfbarry.concat(qualityHandingRate, TestCoverage, MeasureQuality, TestPassRate, LeakRateMeasurement)
    let sql = 'INSERT INTO qualityfactor(singlequalityRegression,singlequalityHandingRate,SingleTestCoverage,SingleMeasureQuality,SingleTestPassRate,SingleLeakRateMeasurement,qualitysum) values(?,?,?,?,?,?,?) '
    let args = [JSON.stringify(bfbarry), JSON.stringify(qualityHandingRate), JSON.stringify(TestCoverage), JSON.stringify(MeasureQuality), JSON.stringify(TestPassRate), JSON.stringify(LeakRateMeasurement), JSON.stringify(sumarry)]

    await Pool.queryAsync(sql, args)
  }


  async getSingleBugNumWeekGrowth(idArry) {

    let retsingleWeekGrowth = []
    for (let i of idArry) {
      let ret = 0;
      let oneWeek = await this.getBugByJql({
        jql: `project = ${i} AND created >= -1w`
      });

      let twoWeek = await this.getBugByJql({
        jql: `project = ${i} AND created >= -2w`
      });
      let prev = twoWeek.total - oneWeek.total;
      let next = oneWeek.total;
      if (prev == 0 || next == 0) {
        ret = 0;

        retsingleWeekGrowth.push(parseInt(ret))
      }
      else {

        ret = (next - prev) / prev;

        retsingleWeekGrowth.push(ret.toFixed(1))

      };


    }


    return retsingleWeekGrowth;
  };


  async getSingleBugNumDayGrowth(idArry) {

    let retsingleDayGrowth = []
    for (let i of idArry) {
      let ret = 0;
      let oneDay = await this.getBugByJql({
        jql: `project = ${i} AND created >= -1d`
      });
      let twoDay = await this.getBugByJql({
        jql: `project = ${i} AND created >= -2d`
      });
      let prev = twoDay.total - oneDay.total;
      let next = oneDay.total;
      if (prev == 0 || next == 0) {
        ret = 0;

        retsingleDayGrowth.push(parseInt(ret))
      }
      else {

        ret = (next - prev) / prev;

        retsingleDayGrowth.push(ret.toFixed(1))

      };
    }
    return retsingleDayGrowth;
  };

  // 挂起率
  async getBugSingleHandingRate(idArry) {

    let bugtotal = await this.getSingleBugByJql(idArry)
    let resTotal = []
    let retsingleHandingRate = [];
    for (let i of idArry) {
      let ret = 0;
      let res = await this.getBugByJql({
        jql: `project = ${i} AND status = %e6%8c%82%e8%b5%b7 `
      });

      resTotal.push(res.total)
    }

    resTotal.forEach((item, index) => {
      let m = bugtotal[index];
      retsingleHandingRate.push(((item / m) * 100).toFixed(1));
    })

    return retsingleHandingRate;
  }


  //挂起率周比
  async getBugSingleHandingWeekGrowth(idArry) {

    let retsingleHandingWeeKGrowth = []
    for (let i of idArry) {
      let ret = 0;
      let oneWeek = await this.getBugByJql({
        jql: `project = ${i} AND created >= -1w`
      });

      let twoWeek = await this.getBugByJql({
        jql: `project = ${i} AND created >= -2w`
      });

      let prev = twoWeek.total - oneWeek.total;
      let next = oneWeek.total;
      if (prev == 0 || next == 0) {
        ret = 0;

        retsingleHandingWeeKGrowth.push(parseInt(ret))

      }
      else {

        ret = (next - prev) / prev;

        retsingleHandingWeeKGrowth.push(ret.toFixed(1))

      }
    }
    return retsingleHandingWeeKGrowth;
  }


  async getBugSingleHandingDayGrowth(idArry) {

    let retsingleHandingDayGrowth = []
    for (let i of idArry) {
      let ret = 0;
      let oneDay = await this.getBugByJql({
        jql: `project = ${i} AND created >= -1d`
      });
      let twoDay = await this.getBugByJql({
        jql: `project = ${i} AND created >= -2d`
      });
      let prev = twoDay.total - oneDay.total;
      let next = oneDay.total;
      if (prev == 0 || next == 0) {
        ret = 0;

        retsingleHandingDayGrowth.push(parseInt(ret))

      }
      else {

        ret = (next - prev) / prev;

        retsingleHandingDayGrowth.push(ret.toFixed(1))

      };
    }
    return retsingleHandingDayGrowth;
  }


  //30天内每个项目新建数
  async getBugSingleMonthDetail(idArry) {

    let ret = [];
    for (let i of idArry) {

      let arr = [];
      for (let j = 0; j < 30; j++) {
        let nowDate = TimeTool.getDate(29 - j);
        let nextDate = TimeTool.getDate(28 - j);
        let res = await this.getBugByJql({
          jql: `project = ${i} AND created >= ${nowDate} AND created <= ${nextDate}`
        });
        arr.push({
          x: nowDate,
          y: res.total,
          id: i

        });

      }
      ret.push(arr)

    }
    return ret

  }


  //30天内总数
  async getSingleBugMonthTotal(idArry) {

    let BugMonthTotal = await this.getBugSingleMonthDetail(idArry)
    let sumarry = [];
    for (let i in BugMonthTotal) {
      let sum = 0;
      let arry = BugMonthTotal[i]
      for (let j in arry) {
        sum += arry[j].y
      }
      sumarry.push(sum)
    };
    return sumarry;

  }


  //30天单日最大数
  async getSingleBugMonthMax(idArry) {

    let maxarry = [];
    let BugMonthTotal = await this.getBugSingleMonthDetail(idArry)
    for (let i in BugMonthTotal) {

      let max = 0;
      let arry = BugMonthTotal[i]

      for (let j in arry) {
        if (arry[j].y > max) {
          max = arry[j].y;
        };
      };
      maxarry.push(max)


    }
    return maxarry;
  }


  async getSingleBugDayAverage(idArry) {

    let singldaysAverageBug = []
    let singlebugTotal = await this.getSingleBugByJql(idArry)
    let singleDays = await this.getSingleProjectStartDate(idArry)
    for (let i = 0; i < idArry.length; i++) {
      let res = !Math.round(singlebugTotal[i] / singleDays[i])? 0:Math.round(singlebugTotal[i] / singleDays[i])
      singldaysAverageBug.push(res)
    }
    return singldaysAverageBug


  }


  async getSingleProjectStartDate(idArry) {

    let firstTimeArry = []
    let days = []
    for (let j = 0; j < idArry.length; j++) {
      let api = `${JIRA_HOST}/rest/api/2/project/${idArry[j]}/versions`
      let res = await request.getAsync(api, user);
      let ret = JiraTool.bodyParser(res);
      let startDateArry = []
      let firstTime = []
      for (let i = 0; i < ret.length; i++) {
        startDateArry.push(ret[i].startDate)
        firstTime = startDateArry.sort()
      }
      firstTimeArry.push(firstTime[0])

    }

    for (let k = 0; k < firstTimeArry.length; k++) {
      days.push(TimeTool.getDays(firstTimeArry[k]))
    }

    return days
  }



  async getSingleProjectName(idArry) {

    let projArrayName = [];
    for (let i = 0; i < idArry.length; i++) {
      let projects = await this.getProjectByIdparma(idArry[i]);
      projArrayName.push(projects.name)

    }

    return projArrayName;


  }


  /**
   * 根据传入JQL从Jira服务器上获取单个项目的Bug数据
   */
  async getSingleBugByJql(jqlId) {

    let res
    let ret
    let retsinglebugtotal = []

    for (let i of jqlId) {
      let api = `${JIRA_HOST}/rest/api/2/search?maxResults=0&jql=project=${i}`
      res = await request.getAsync(api, user);
      ret = JiraTool.bodyParser(res);
      retsinglebugtotal.push(ret.total)
    }

    return retsinglebugtotal
  };

  // 根据jql 条件为 严重程度过滤严重，致命

  async getBugLever(id) {

    const question = '%e9%97%ae%e9%a2%98%e5%85%b3%e9%97%ad'
    const yzchendu = '%e4%b8%a5%e9%87%8d%e7%a8%8b%e5%ba%a6'
    const yanzhong = '%e4%b8%a5%e9%87%8d'
    const zhiming = '%e8%87%b4%e5%91%bd'
    const JQLINSTER = `project = ${id} AND issuetype = Bug AND status = ${question} AND ${yzchendu} in (${yanzhong}, ${zhiming}) `;
    let api = `${JIRA_HOST}/rest/api/2/search?jql=${JQLINSTER}&maxResults=0`;
    let res = await request.getAsync(api, user)
    let ret = JSON.parse(res.body) // 必须转化成json 才能对象取值

    return ret.total;
  };



  // 传递项目ID 得到相关项目数据,不传等于所有项目信息

  async getProjectIdLeve(id) {

    let api = `${JIRA_HOST}/rest/api/2/project`;
    if (id) {
      api += `/${id}`;
    }
    let res = await request.getAsync(api, {
      'auth': {
        username: 'pengs',
        password: '123456'
      }
    });
    let ret = JSON.parse(res.body);
    let filterIDRet = await JiraTool.filterID(ret) // 过滤ID
    return filterIDRet;
  };

  //单个项目每个月的bug数量

  async getProjectEachMonthTotalBug(idArry) {
    const newlyCreated = '%e6%96%b0%e5%88%9b%e5%bb%ba'
    const processing = '%e5%a4%84%e7%90%86%e4%b8%ad'
    const hang = '%e6%8c%82%e8%b5%b7'
    const ProblemClosed = '%e9%97%ae%e9%a2%98%e5%85%b3%e9%97%ad'

    let getEachMonthDaysArray = TimeTool.getEachMonthDays()
    let sumEachMonothBugtotal = []

    for (let j = 0; j < idArry.length; j++) {

      let EachArray = []
      for (let i of getEachMonthDaysArray) {

        let api = `${JIRA_HOST}/rest/api/2/search?jql=project = ${idArry[j]} AND status 
        in (${newlyCreated}, ${processing},${hang}, ${ProblemClosed}) AND created >= ${i.firstDay} AND created <= ${i.lastDay}`
        let res = await request.getAsync(api, user)
        let ret = JSON.parse(res.body) // 必须转化成json 才能对象取值
        let total = ret.total

        EachArray.push({
          x: i.m + '月',
          y: total

        })
      }
      sumEachMonothBugtotal.push(EachArray)
    }

    return sumEachMonothBugtotal

  };


  async getBugAllMonthTotalBug() {

    const newlyCreated = '%e6%96%b0%e5%88%9b%e5%bb%ba'
    const processing = '%e5%a4%84%e7%90%86%e4%b8%ad'
    const hang = '%e6%8c%82%e8%b5%b7'
    const ProblemClosed = '%e9%97%ae%e9%a2%98%e5%85%b3%e9%97%ad'
    const resolved = '%e5%b7%b2%e8%a7%a3%e5%86%b3'
    const refused = '%e6%8b%92%e7%bb%9d'

    let getEachMonthDaysArray = TimeTool.getEachMonthDays()
    let sumallMonothBugtotal = []
    let EachArray = []

    for (let i of getEachMonthDaysArray) {

      let api = `${JIRA_HOST}/rest/api/2/search?jql=project in ('10208', '10700', '11100', '10300', '10204', '10907', '10100', '11104', '11106',
        '11107', '10901', '11105', '11004', '10704') AND status in (${newlyCreated}, ${processing},${hang}, ${ProblemClosed}) AND created >= ${i.firstDay} AND created <= ${i.lastDay}`
      let res = await request.getAsync(api, user)
      let ret = JSON.parse(res.body) // 必须转化成json 才能对象取值
      let total = ret.total

      sumallMonothBugtotal.push({
        x: i.m + '月',
        y: total

      })

    }
    return sumallMonothBugtotal


  }

  // 质量系数内方法
  async SinglequalityHandingRate(idArry) {
    const qualityHandingRate = []
    let value = 0;
    let projects = await this.getProjectById();
    for (let i in projects) {
      let handingRate = 0;
      let { id, name } = projects[i];
      let projectBug = await this.getBugByJql({ jql: `project = ${id}` });
      let { total } = projectBug;
      let projectHandUp = await this.getBugByJql({ jql: `project = ${id} AND status = %e6%8c%82%e8%b5%b7` });
      if (total !== 0) {
        handingRate = projectHandUp.total / total * 100;
      };
      if(handingRate<3){
        value = 5
      }else if(handingRate<6){
        value = 4
      }else if(handingRate<10){
        value = 3
      }else if(handingRate<=20){
        value = 2
      }else{
        value = 1
      }

      qualityHandingRate.push({
        name: name,
        label: '挂起率',
        value: value
      })
    };

    
    return qualityHandingRate

  }


  async SinglequalityRegressionTestRate(idArry) {

    const newlyCreated = '%e6%96%b0%e5%88%9b%e5%bb%ba',
      processing = '%e5%a4%84%e7%90%86%e4%b8%ad',
      hang = '%e6%8c%82%e8%b5%b7',
      ProblemClosed = '%e9%97%ae%e9%a2%98%e5%85%b3%e9%97%ad',
      resolved = '%e5%b7%b2%e8%a7%a3%e5%86%b3',
      refused = '%e6%8b%92%e7%bb%9d',
      ReturnNumber = '%e5%9b%9e%e5%bd%92%e6%ac%a1%e6%95%b0',
      reopenCount = 'reopen%e6%ac%a1%e6%95%b0'

    let bfbarry = []
    for (let i = 0; i < idArry.length; i++) {

      let projectname = this.retSingleProjectName[i]

      let sum = 0
      let sumreopen = 0
      let bfb = 0

      for (let j = 1; j <= 15; j++) {

        let api = `${JIRA_HOST}/rest/api/2/search?jql=project = ${idArry[i]} AND status in 
        (${newlyCreated},${processing},${hang},${ProblemClosed},${resolved},${refused})
        AND ${ ReturnNumber}<= ${j} AND ${ReturnNumber} >= ${j}`;

        let api2 = `${JIRA_HOST}/rest/api/2/search?jql=project = ${idArry[i]} AND status in
        (${newlyCreated},${processing},${hang},${ProblemClosed},${resolved},${refused})
        AND  ${reopenCount} <= ${j}  AND  ${reopenCount} >= ${j}`


        let res = await request.getAsync(api, user)
        let ret = JSON.parse(res.body)
        let total = ret.total * j
        sum += total

        let resreopen = await request.getAsync(api2, user)
        let retreopen = JSON.parse(resreopen.body)
        let reopentotal = retreopen.total * j

        sumreopen += reopentotal

      }


      bfb = ((sum - sumreopen) / sum * 100).toFixed(0);
      if (bfb == 100) {
        let score = 5
        bfbarry.push({
          name: projectname,
          label: '回归测试通过率',
          value: score
        })
      }

      else if (95 < bfb && bfb < 100) {
        let score = 4
        bfbarry.push({
          name: projectname,
          label: '回归测试通过率',
          value: score
        })
      }

      else if (85 < bfb && bfb <= 95) {
        let score = 3
        bfbarry.push({
          name: projectname,
          label: '回归测试通过率',
          value: score
        })
      }
      else if (75 <= bfb && bfb <= 85) {
        let score = 2
        bfbarry.push({
          name: projectname,
          label: '回归测试通过率',
          value: score
        })
      }
      else {
        let score = 1
        bfbarry.push({
          name: projectname,
          label: '回归测试通过率',
          value: score
        })
      }

    }
    return bfbarry
  }


  async SingleTestCoverage(idArry) {

    let TestCoverage = []

    for (let i = 0; i < idArry.length; i++) {

      let projectname = this.retSingleProjectName[i]


      TestCoverage.push({
        name: projectname,
        label: '测试覆盖率',
        value: 3
      })
    }

    return TestCoverage

  }

  async SingleMeasureQuality(idArry) {

    let measureQuality = []
    let quality = []
    let projectlist = await Project.list()
    if(projectlist.length>0){
      quality = await TestRecord.launchTestQuality(projectlist)
    }

    if(quality.length>0){
      for (let i = 0; i < idArry.length; i++) {
        let count = 0
        let projectname = this.retSingleProjectName[i]
        for(let a = 0;a< quality.length;a++){
          if(quality[a].name===projectname){
            measureQuality.push(quality[a])
            count +=1
          }
        }
        if(count ==0){
          measureQuality.push({
            name: projectname,
            label: '提测质量',
            value: 0
          })
        }
      }
    }else{
      for (let i = 0; i < idArry.length; i++) {
        let projectname = this.retSingleProjectName[i]
        measureQuality.push({
          name: projectname,
          label: '提测质量',
          value: 0
        })
      }
    }

    

    return measureQuality


  }
  async SingleTestPassRate(idArry) {

    let TestPassRate = []
    let passrate = []
    let projectlist = await Project.list()
    if(projectlist.length>0){
      passrate = await TestReport.passRate(projectlist)
    }
    if(passrate.length>0){
      for (let i = 0; i < idArry.length; i++) {
        let count = 0
        let projectname = this.retSingleProjectName[i]
        for(let a = 0;a< passrate.length;a++){
          if(passrate[a].name===projectname){
            TestPassRate.push(passrate[a])
            count +=1
          }
        }
        if(count ==0){
          TestPassRate.push({
            name: projectname,
            label: '测试通过率',
            value: 0
          })
        }
      }
    }else{
      for (let i = 0; i < idArry.length; i++) {
        let projectname = this.retSingleProjectName[i]
        TestPassRate.push({
          name: projectname,
          label: '测试通过率',
          value: 0
        })
      }
    }
    return TestPassRate

  }


  async SingleLeakRateMeasurement(idArry) {

    let LeakRateMeasurement = []

    let leakTestCount = await this.getBugLeakTestCount();

    for (let i = 0; i < leakTestCount.length; i++) {
      let name = leakTestCount[i].pname
      let leak = leakTestCount[i].leakRate
      let value = 0
      
      if(leak<0.0005){
        value = 5
      }else if(leak < 0.005){
        value = 4
      }else if(leak < 0.01){
        value = 3
      }else if(leak<=0.04){
        value = 2
      }else{
        value = 1
      }

      LeakRateMeasurement.push({
        name: name,
        label: '漏测率',
        value: value
      })
    }

    return LeakRateMeasurement


  }

  async  getBugLeakTestCount() {
    let selectResult =await  this.getCountByCustomField("发现阶段");
    let extraProject = await JiraTool.getExtraProjectArr();
  
    let leakTestCount = []
  
    _.forEach(extraProject, pid => {
      let filterResult = _.filter(selectResult, (d) => {
        return d.pid == pid;
      });
      let total = 0;
      let leak = 0;
      if (filterResult.length > 0) {
        let result = { pid: filterResult[0].pid, pname: filterResult[0].pname };
        _.forEach(filterResult, (fr) => {
          let key = fr.customValue;
          let value = fr.customValueCount;
          total += fr.customValueCount;
          if(key == "用户反馈"){
            leak = value;
          }
          // _.merge(result, { [key]: value });
        })
        let leakRate = total == 0 || leak == 0 ? 0 : leak / total;
        _.merge(result, {total, leakCount:leak, leakRate,  })
        leakTestCount.push(result);
      }
    });
    return leakTestCount;
  }


}



const bL = new JiraModel();

module.exports = new JiraModel();